package codingforgreat.lchot150;

import java.util.ArrayList;

public class Lc207 {
    public boolean canFinish(int numCourses, int[][] prerequisites) {
        ArrayList<ArrayList<Integer>> nexts = new ArrayList<>();
        for(int i = 0;i < numCourses;i++){
            nexts.add(new ArrayList<>());
        }
        int[] in = new int[numCourses];
        for(int i = 0;i < prerequisites.length;i++){
            int from = prerequisites[i][0];
            int to = prerequisites[i][1];
            nexts.get(from).add(to);
            in[to]++;
        }
        int[] zeroQueue = new int[numCourses];
        int L = 0;
        int R = 0;
        for(int i = 0;i < numCourses;i++){
            if(in[i] == 0){
                zeroQueue[R++] = i;
            }
        }
        int count = 0;
        while(L < R){
            int cur = zeroQueue[L++];
            count++;
            for(int next : nexts.get(cur)){
                in[next]--;
                if(in[next] == 0){
                    zeroQueue[R++] = next;
                }
            }
        }
        return count == numCourses;
    }
}
